package com.summer.web.v1.base.jmx.factory;

import org.jolokia.jmx.JolokiaMBeanServerUtil;

import javax.annotation.PostConstruct;
import javax.management.*;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JolokiaMBeanFactory {

    Logger logger = Logger.getLogger(this.getClass().getName());

    @PostConstruct
    public void initialJolokiaMBean() {
        MBeanServer jolokiaMBeanServer = JolokiaMBeanServerUtil.getJolokiaMBeanServer();
        try {
            for (JolokiaMBeanRegister item : getMBeanRegisters()) {
                jolokiaMBeanServer.registerMBean(item.register().typeClass, item.register().objectName);
                boolean registered = jolokiaMBeanServer.isRegistered(item.register().objectName);
                if (registered) {
                    logger.info(item.register().objectName + "MBean 注册成功");
                }
            }
        } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
            e.printStackTrace();
            logger.log(Level.SEVERE, "jolokia MBean 注册失败", e.getMessage());
        }
    }

    private List<JolokiaMBeanRegister> getMBeanRegisters() {
        return Arrays.asList(
                new UserJolokiaMBean()
        );
    }

}
